﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ZXing;
using ZXing.Net.Mobile.Forms;

namespace ZXXFAPP.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ScanPage : ContentPage
    {
        //public bool CanExit = false;
        public ScanPage()
        {
            InitializeComponent();

        }

        public void StartScanning()
        {
            scanner.Options = new ZXing.Mobile.MobileBarcodeScanningOptions
            {
                PossibleFormats = new List<ZXing.BarcodeFormat>
                {
                    BarcodeFormat.QR_CODE,
                    //BarcodeFormat.CODE_128,                    
                    //BarcodeFormat.EAN_13,
                    //BarcodeFormat.EAN_8,
                    //BarcodeFormat.CODE_39,
                    //BarcodeFormat.CODE_93
                }
            };
            scanner.IsScanning = true;
            //CanExit = false;
            scanner.OnScanResult += (result) => {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    labResult.Text = result.Text;
                });
                Device.BeginInvokeOnMainThread(async () =>
                {                    
                    //弹出对话框显示扫描结果
                    //await Application.Current.MainPage.DisplayAlert("Scanned Result", result.Text, "OK");
                      
                    Thread.Sleep(800);
                    scanner.IsScanning = false;
                    //await DisplayAlert("Scanned Result", result.Text, "OK");
                    await Shell.Current.Navigation.PopModalAsync();
                    Trace.WriteLine("Scaned barcode aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: " + result.Text);
                    MessagingCenter.Send<ScanPage,string>(this,"BarcodeScanResult", result.Text);
                });
            };
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();

            StartScanning();
            CancelBtn.Clicked += async (s, e) =>
            {
                scanner.IsScanning = false;
                await Shell.Current.Navigation.PopModalAsync();
            };
        }

        protected override void OnDisappearing()
        {
            if (scanner.IsScanning)
            {
                Trace.WriteLine("wrong exit; BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
                return;//do not stop scanning
            }
            scanner.IsScanning = false;
            Trace.WriteLine("CCCCCCCCCCCCCCCCCCCCCCCCCCCC");

           base.OnDisappearing();
        }
    }
}